package com.innovatio.validator.handlers;

import com.innovatio.validator.annotations.ValidateExpresion;
import com.innovatio.validator.ValidationErrors;
import com.innovatio.validator.Validable;
import com.innovatio.validator.exceptions.ValidatorException;
import com.innovatio.utils.general.CommonsUtils;
import com.innovatio.utils.bean.BeanExpresionEvaluator;


/**
 * This code is property of Innovatio Software Solutions, Inc.
 * User: Edxe
 * Date: Jul 8, 2009
 * Time: 2:55:54 AM
 */
public class ValidateExpresionHandler implements ValidationHandler<ValidateExpresion> {

    @Override
    public ValidationErrors.Error validate(ValidateExpresion annotation, Validable container, String fieldName, String value) throws ValidatorException {


        try {

            BeanExpresionEvaluator ev = BeanExpresionEvaluator.newInstance(container, annotation.expresion());
            getExpresionVars(annotation.varValues(), ev);
            Boolean result = ev.evaluate();
            if (!result) {
                return new ValidationErrors.Error(fieldName, annotation.i18nBundleKey());
            }


            return null;

        } catch (Exception e1) {
            throw new ValidatorException(e1);
        }


    }

    private void getExpresionVars(String varValues, BeanExpresionEvaluator ev) {


        if (CommonsUtils.isStringEmpty(varValues))
            return;


        String[] varVals = varValues.split("[,]");
        for (String s : varVals) {
            String temp[] = s.split("[:]");
            ev.addParameters(temp[0], temp[1]);
        }

    }


}
